package com.pureut.storage.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.StringUtils;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.storage.domain.*;
import com.pureut.storage.dto.*;
import com.pureut.storage.export.CheckManagementExport;
import com.pureut.storage.mapper.*;
import com.pureut.storage.service.*;
import com.pureut.storage.utils.DocumentTypeEnum;
import com.pureut.storage.utils.GenerationMethodEnum;
import com.pureut.storage.vo.*;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.SysWorkbenchAuditAgentVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: CM
 * @date: 2023/1/13  11:11
 */
@Service
public class CheckManagementServiceImpl extends ServiceImpl<CheckManagementMapper, CheckManagement> implements CheckManagementService {

    @Resource
    private CheckManagementMapper checkManagementMapper;

    @Resource
    private CheckManagementDetailMapper checkManagementDetailMapper;

    /**
     * 物料明细Service
     */
    @Resource
    CheckManagementMaterialDetailService checkManagementMaterialDetailService;

    @Resource
    private CheckManagementMaterialDetailMapper checkManagementMaterialDetailMapper;

    @Resource
    private PublicGoodsMapper publicGoodsMapper;

    @Resource
    private WarehouseService warehouseService;

    @Resource
    private WarehouseMapper warehouseMapper;

    @Resource
    private WmsStockInfoMapper wmsStockInfoMapper;

    @Resource
    private WmsStockInfoService wmsStockInfoService;

    @Resource
    private CheckManagementDetailService checkManagementDetailService;

    @Resource
    FeignService feignService;

    //其他出库
    @Resource
    private PickingRestService pickingRestService;

    @Resource
    private PickingRestMapper pickingRestMapper;

    @Resource
    private PickingRestDetailService pickingRestDetailService;

    @Resource
    private PickingRestDetailMapper pickingRestDetailMapper;

    /**
     * 新增物料盘点
     *
     * @param addCheckVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addCheck(AddCheckVo addCheckVo) throws Exception {

        String sn = feignService.getAuthorityCoding("warehouse:inside:inventoryCount:list");
        if (sn == null) {
            throw new GlobalException("该单据未进行配置,无法生成单据编码");
        }

        //新增盘点单信息
        CheckManagement checkManagement = new CheckManagement();
        BeanUtils.copyProperties(addCheckVo, checkManagement);
        //盘点单号
        checkManagement.setCheckDoc(sn);
        //盘点状态
        checkManagement.setCheckStatus("1");
        checkManagement.setDeptId(SecurityUtils.getDeptId());
        checkManagement.setCreateTime(new Date());
        checkManagement.setCreateUser(SecurityUtils.getUsername());
        checkManagement.setDeptId(SecurityUtils.getDeptId());

        boolean save = save(checkManagement);
        if (save) {
            //新增盘点单单据信息
            List<CheckManagementVo> docList = addCheckVo.getDocList();

            List<CheckManagementDetail> list = new ArrayList<>();

            for (CheckManagementVo checkManagementVo : docList) {
                CheckManagementDetail checkManagementDetail = new CheckManagementDetail();
                BeanUtils.copyProperties(checkManagementVo, checkManagementDetail);
                checkManagementDetail.setStatus("1");
                checkManagementDetail.setCheckDoc(checkManagement.getCheckDoc());
                list.add(checkManagementDetail);
            }
            checkManagementDetailService.saveBatch(list);

            List<CheckManageMaterialVo> materialList = addCheckVo.getMaterialList();


            List<WmsStockInfo> stockInfolist = new ArrayList<>();

            List<CheckManagementMaterialDetail> checkManagementMaterialDetailList = new ArrayList<>();


            for (CheckManageMaterialVo checkManageMaterialVo : materialList) {

                //修改仓库状态为盘点
                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, checkManageMaterialVo.getMaterialNumber()));
                if (wmsStockInfo != null) {
                    wmsStockInfo.setWsiMaterialStatus(4);
                    stockInfolist.add(wmsStockInfo);
                }

                CheckManagementMaterialDetail checkManagementMaterialDetail = new CheckManagementMaterialDetail();

                BeanUtils.copyProperties(checkManageMaterialVo, checkManagementMaterialDetail);

                //设置状态为待盘点
                checkManagementMaterialDetail.setMaterialStatus("1");

                checkManagementMaterialDetail.setCheckDoc(checkManagement.getCheckDoc());
                checkManagementMaterialDetailList.add(checkManagementMaterialDetail);

            }
            wmsStockInfoService.updateBatchById(stockInfolist);
            checkManagementMaterialDetailService.saveBatch(checkManagementMaterialDetailList);
        }
        return save;
    }

    /**
     * 删除单据
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String ids) {
        //将ids根据逗号拆分成数组
        List<String> idStr = Arrays.asList(ids.split(","));
        if (idStr.size() == 0) {
            throw new GlobalException("请至少勾选一条单据");
        }
        List<CheckManagement> checkManagements = checkManagementMapper.selectList(new QueryWrapper<CheckManagement>().lambda().in(CheckManagement::getId, idStr));
        for (CheckManagement checkManagement : checkManagements) {
            if ("1".equals(checkManagement.getCheckStatus())) {

                List<CheckManagementDetail> checkManagementDetail = checkManagementDetailMapper.selectList(new QueryWrapper<CheckManagementDetail>().lambda().eq(CheckManagementDetail::getCheckDoc, checkManagement.getCheckDoc()));
                if (checkManagementDetail.size() > 0) {
                    checkManagementDetailMapper.deleteBatchIds(checkManagementDetail);
                }
                List<CheckManagementMaterialDetail> checkManagementMaterialDetails = checkManagementMaterialDetailMapper.selectList(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getCheckDoc, checkManagement.getCheckDoc()));
                if (checkManagementMaterialDetails.size() > 0) {

                    List<String> materialNumbers = new ArrayList<>();
                    for (CheckManagementMaterialDetail entity : checkManagementMaterialDetails) {
                        materialNumbers.add(entity.getMaterialNumber());
                    }
                    List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumbers));
                    for (WmsStockInfo wmsStockInfo : wmsStockInfoList) {
                        wmsStockInfo.setWsiMaterialStatus(2);
                    }
                    wmsStockInfoService.updateBatchById(wmsStockInfoList);
                    checkManagementMaterialDetailMapper.deleteBatchIds(checkManagementMaterialDetails);
                }
            } else {
                throw new GlobalException("只能删除待盘点状态的单据");
            }
        }
        return removeBatchByIds(checkManagements);
    }

    /**
     * 关结单据
     *
     * @param checkCloseVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean close(CheckCloseVo checkCloseVo) {
        CheckManagementDetail checkManagementDetail = checkManagementDetailMapper.selectById(checkCloseVo.getId());
        String checkStatus = checkManagementDetail.getStatus();
        if ("5".equals(checkStatus)) {
            throw new GlobalException("不可对状态为已关结的单据进行重复关结");
        }

        //修改明细状态为已关节，新增关节原因，关节时间
        checkManagementDetail.setCloseCause(checkCloseVo.getCloseCause());
        checkManagementDetail.setCloseTime(new Date());
        checkManagementDetail.setCloseUser(SecurityUtils.getUsername());
        checkManagementDetail.setStatus("5");
        int i = checkManagementDetailMapper.updateById(checkManagementDetail);

        //修改物料明细状态为已经关节
        List<CheckManagementMaterialDetail> checkManagementMaterialDetailList = checkManagementMaterialDetailMapper.selectList(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getCheckDoc, checkManagementDetail.getCheckDoc()).eq(CheckManagementMaterialDetail::getMaterialCode, checkManagementDetail.getMaterialCode()));
        List<CheckManagementMaterialDetail> list = new ArrayList<>();
        List<WmsStockInfo> wmsStockInfoList = new ArrayList<>();
        for (CheckManagementMaterialDetail checkManagementMaterialDetail : checkManagementMaterialDetailList) {
            checkManagementMaterialDetail.setMaterialStatus("5");
            list.add(checkManagementMaterialDetail);

            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, checkManagementMaterialDetail.getMaterialNumber()));
            wmsStockInfo.setWsiMaterialStatus(2);
            wmsStockInfoList.add(wmsStockInfo);

        }
        //修改仓库物料状态为在库
        wmsStockInfoService.updateBatchById(wmsStockInfoList);

        boolean b = checkManagementMaterialDetailService.updateBatchById(list);

        //盘点单据明细中的所有物料是否已全部关节，如果是修改盘点单状态为已关节
        if (b) {
            //单据明细全部关结标识
            boolean flag = true;
            //查询当前盘点单号对应的所有单据明细
            List<CheckManagementDetail> checkManagementDetails = checkManagementDetailMapper.selectList(new QueryWrapper<CheckManagementDetail>().lambda().eq(CheckManagementDetail::getCheckDoc, checkManagementDetail.getCheckDoc()));
            for (CheckManagementDetail managementDetail : checkManagementDetails) {
                String status = managementDetail.getStatus();
                if (!"5".equals(status)) {
                    flag = false;
                }
            }
            if (flag) {
                List<CheckManagement> checkManagements = checkManagementMapper.selectList(new QueryWrapper<CheckManagement>().lambda().eq(CheckManagement::getCheckDoc, checkManagementDetail.getCheckDoc()));
                List<CheckManagement> checkManagementList = new ArrayList<>();
                for (CheckManagement checkManagement : checkManagements) {
                    checkManagement.setCheckStatus("6");
                    checkManagementList.add(checkManagement);
                }
                updateBatchById(checkManagementList);
            }
        }
        return b;
    }

    /**
     * 导出
     *
     * @param checkManagementVo
     * @return
     */
    @Override
    public List<CheckManagementExport> getInfoExport(CheckManagementVo checkManagementVo) {
        List<CheckManagementExport> list;
        if (checkManagementVo.getIdStr() != null) {
            List<String> idList = Arrays.asList(checkManagementVo.getIdStr().split(","));

            checkManagementVo.setIds(idList);

            list = checkManagementMapper.getInfoExport(checkManagementVo);
        }
        list = checkManagementMapper.getInfoExport(checkManagementVo);

        //盘点类型
        List<SysDictData> typeArray = DictUtils.getDictCache("check_management_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (CheckManagementExport checkManagementExport : list) {
            checkManagementExport.setCheckType(typeMap.get(checkManagementExport.getCheckType()));
        }

        return list;
    }

    /**
     * 审核单据
     *
     * @param orderReviewVo
     * @return
     */
    @Override
    public boolean checkManagementReview(OrderReviewVo orderReviewVo) {
        /*
        CheckManagement checkManagement = getById(orderReviewVo.getId());
        if ("3".equals(checkManagement.getCheckStatus()) || "4".equals(checkManagement.getCheckStatus())) {
            String perms = "warehouseinside:InventoryCount:examine";
            int isAdopt = orderReviewVo.getIsAdopt();
            String auditDoc = checkManagement.getCheckDoc();
            String auditRemarks = orderReviewVo.getReviewComments();
            Long userId = SecurityUtils.getUserId();
            AjaxResult sequence = feignService.getSequenceTwo(perms, 9, isAdopt, auditRemarks, auditDoc, userId);
            Integer data = JSON.parseObject(JSON.toJSONString(sequence.get("data")), Integer.class);
            if (data == null) {
                throw new GlobalException("未对该审核进行配置");
            }
            //1:通过，2：审核中，3：没权限 4:该人已经审核过
            if (orderReviewVo.getIsAdopt() == 1) {
                if (data == 1) {
                    checkManagement.setWodStatus(5);
                    if (pickingOutsource.getReviewBy() == null) {
                        pickingOutsource.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        pickingOutsource.setReviewBy(pickingOutsource.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    pickingOutsource.setReviewTime(new Date());

                    return updateById(pickingOutsource);
                } else if (data == 2) {
                    pickingOutsource.setWodStatus(3);
                    if (pickingOutsource.getReviewBy() == null) {
                        pickingOutsource.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        pickingOutsource.setReviewBy(pickingOutsource.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    pickingOutsource.setReviewTime(new Date());
                    return updateById(pickingOutsource);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            } else {
                if (data == 1 || data == 2) {
                    pickingOutsource.setWodStatus(4);
                    if (pickingOutsource.getReviewBy() == null) {
                        pickingOutsource.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        pickingOutsource.setReviewBy(pickingOutsource.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    pickingOutsource.setReviewTime(new Date());
                    return updateById(pickingOutsource);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            }
        } else {
            throw new GlobalException("状态为待审核和审核中的单据才能进行审核");
        }
        */

        return true;
    }

    /**
     * 盘点物料下拉
     *
     * @param id
     * @return
     */
    @Override
    public List<CheckMaterialDto> getMaterial(Long id) {
        CheckManagement checkManagement = checkManagementMapper.selectById(id);
        List<CheckMaterialDto> list = checkManagementDetailMapper.selectMaterialList(checkManagement.getCheckDoc());
        return list;
    }

    /**
     * 盘点审核单据明细
     *
     * @param id
     * @return
     */
    @Override
    public List<CheckManagementDto> reviceDocDetail(Long id) {

        CheckManagement checkManagement = getById(id);

        List<CheckManagementDto> list = checkManagementDetailMapper.reviceDocDetail(checkManagement.getCheckDoc());
        return list;
    }

    /**
     * 盘点审核物料明细
     *
     * @param id
     * @return
     */
    @Override
    public List<CheckManagmentMaterialDto> reviceMaterialDetail(Long id) {
        CheckManagement checkManagement = getById(id);

        List<CheckManagmentMaterialDto> list = checkManagementMaterialDetailMapper.reviceMaterialDetail(checkManagement.getCheckDoc());
        return list;
    }

    /**
     * 审核回显
     *
     * @param id
     * @return
     */
    @Override
    public CheckDto getRevice(Long id) {
        CheckManagement checkManagement = getById(id);

        if (!"3".equals(checkManagement.getCheckStatus())) {
            throw new GlobalException("只有待审核状态的盘点单可以进行审核操作");
        }


        //盘点类型
        List<SysDictData> typeArray = DictUtils.getDictCache("check_management_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        CheckDto checkDto = new CheckDto();
        checkDto.setId(checkManagement.getId());
        checkDto.setCheckDoc(checkManagement.getCheckDoc());
        checkDto.setCheckDate(checkManagement.getCheckDate());
        checkDto.setCheckType(checkManagement.getCheckType());
        checkDto.setCheckTypeDict(typeMap.get(checkManagement.getCheckType()));

        List<CheckManagementDto> list = checkManagementDetailMapper.reviceDocDetail(checkManagement.getCheckDoc());
        List<SysDictData> checkManagementStatus = DictUtils.getDictCache("check_management_detail_status");
        Map<String, String> checkMap = checkManagementStatus.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (CheckManagementDto checkManagementDto : list) {
            checkManagementDto.setStatusDict(checkMap.get(checkManagementDto.getStatus()));
        }
        checkDto.setList(list);

        List<CheckManagmentMaterialDto> list1 = checkManagementMaterialDetailMapper.reviceMaterialDetail(checkManagement.getCheckDoc());
        List<SysDictData> materialArray = DictUtils.getDictCache("check_management_material_detail_status");
        Map<String, String> materialMap = materialArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (CheckManagmentMaterialDto checkManagmentMaterialDto : list1) {
            checkManagmentMaterialDto.setMaterialStatusDict(materialMap.get(checkManagmentMaterialDto.getMaterialStatus()));
        }

        checkDto.setMaterialList(list1);
        return checkDto;
    }


    /**
     * 审核Ok
     *
     * @param pdVo
     * @return
     */
    @Override
    public boolean reviceOk(PdVo pdVo) {
        CheckManagementDetail checkManagementDetail = checkManagementDetailService.getById(pdVo.getId());
        if (!"2".equals(checkManagementDetail.getStatus())) {
            throw new GlobalException("只有盘点中状态的物料可以进行OK操作");
        }
        checkManagementDetail.setStatus("4");
        return checkManagementDetailService.updateById(checkManagementDetail);
    }

    /**
     * 审核NG
     *
     * @param pdVo
     * @return
     */
    @Override
    public boolean reviceNg(PdVo pdVo) {
        CheckManagementDetail checkManagementDetail = checkManagementDetailService.getById(pdVo.getId());
        if (!"2".equals(checkManagementDetail.getStatus())) {
            throw new GlobalException("只有盘点中状态的物料可以进行NG操作");
        }
        //修改状态为未通过
        checkManagementDetail.setStatus("3");

        boolean update = checkManagementDetailService.updateById(checkManagementDetail);


        if (update) {
            //单据状态为盘点中
            CheckManagement checkManagement = checkManagementMapper.selectOne(new QueryWrapper<CheckManagement>().lambda().eq(CheckManagement::getCheckDoc, checkManagementDetail.getCheckDoc()));
            checkManagement.setCheckStatus("2");
            updateById(checkManagement);

            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.set("check_num", null);
            updateWrapper.set("phase_num", null);
            updateWrapper.set("create_user", null);
            updateWrapper.set("create_time", null);
            updateWrapper.set("material_status", "1");
            updateWrapper.eq("material_code", checkManagementDetail.getMaterialCode());
            updateWrapper.eq("check_doc", checkManagementDetail.getCheckDoc());
            checkManagementMaterialDetailService.update(updateWrapper);
        } else {
            throw new GlobalException("操作失败");
        }


        return update;
    }

    /**
     * 单据审核确定
     *
     * @param orderReviewVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean checkReview(OrderReviewVo orderReviewVo) throws Exception {
        CheckManagement checkManagement = getById(orderReviewVo.getId());

        List<CheckManagementDto> list = checkManagementDetailMapper.reviceDocDetail(checkManagement.getCheckDoc());

        for (CheckManagementDto checkManagementDto : list) {
            if (!"4".equals(checkManagementDto.getStatus()) && !"5".equals(checkManagementDto.getStatus())) {
                throw new GlobalException("只有明细状态全部为“盘点完成、已关结”后，才可进行单据的审核确定");
            }
        }


        if ("3".equals(checkManagement.getCheckStatus()) || "4".equals(checkManagement.getCheckStatus())) {
            String perms = "warehouse:inside:InventoryCount:examine";
            int isAdopt = orderReviewVo.getIsAdopt();
            String auditDoc = checkManagement.getCheckDoc();
            String auditRemarks = orderReviewVo.getReviewComments();
            Long userId = SecurityUtils.getUserId();
            AjaxResult sequence = feignService.getSequenceTwo(perms, 9, isAdopt, auditRemarks, auditDoc, userId);
            Integer data = JSON.parseObject(JSON.toJSONString(sequence.get("data")), Integer.class);
            if (data == null) {
                throw new GlobalException("未对该审核进行配置");
            }
            //1:通过，2：审核中，3：没权限 4:该人已经审核过
            if (orderReviewVo.getIsAdopt() == 1) {
                if (data == 1) {
                    checkManagement.setCheckStatus("5");
                    if (checkManagement.getReviewBy() == null) {
                        checkManagement.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        checkManagement.setReviewBy(checkManagement.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    checkManagement.setReviewTime(new Date());

                    //审核通过后将所有物料修改为在库
                    List<CheckManagementMaterialDetail> checkManagementMaterialDetailList = checkManagementMaterialDetailMapper.selectList(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getCheckDoc, checkManagement.getCheckDoc()).notInSql(CheckManagementMaterialDetail::getMaterialStatus, "5"));
                    List<WmsStockInfo> wmsList = new ArrayList<>();
                    for (CheckManagementMaterialDetail checkManagementMaterialDetail : checkManagementMaterialDetailList) {
                        WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, checkManagementMaterialDetail.getMaterialNumber()));
                        wmsStockInfo.setWsiMaterialStatus(2);
                        wmsList.add(wmsStockInfo);
                    }

                    //修改审核
                    List<WmsStockInfo> wmsStockInfoList = new ArrayList<>();

                    List<PickingRestDetail> restList = new ArrayList<>();

                    //把物料明细中为待盘点状态的设置为盈亏
                    List<CheckManagementMaterialDetail> checkManagementMaterialDetails = checkManagementMaterialDetailMapper.selectList(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getCheckDoc, checkManagement.getCheckDoc()).eq(CheckManagementMaterialDetail::getMaterialStatus, 3));
                    for (CheckManagementMaterialDetail checkManagementMaterialDetail : checkManagementMaterialDetails) {

                        WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, checkManagementMaterialDetail.getMaterialNumber()));

                        //查询其他出库单是否存在
                        PickingRest pickingRest = pickingRestMapper.selectOne(new QueryWrapper<PickingRest>().lambda().eq(PickingRest::getConnectionId, checkManagement.getCheckDoc()));
                        //如果不存在其他出库单
                        if (pickingRest == null) {
                            PickingRest pickingRest1 = new PickingRest();
                            pickingRest1.setDeptId(SecurityUtils.getDeptId())
                                    .setWodDocNum(feignService.splitList("TC"))
                                    .setConnectionId(checkManagement.getCheckDoc())
                                    .setWodStatus(3)//已完成
                                    .setDateDelivery(new Date())
                                    .setMaterialCode(checkManagementMaterialDetail.getMaterialCode())
                                    .setPlannedWeight(0.0)
                                    .setOutgoingWeight(0.0)
                                    .setOutgoingNumber(0)
                                    .setActualNumber(0.0)
                                    .setTransceiverType(1)
                                    .setDocumentType(DocumentTypeEnum.PICKING_REST.getCode())
                                    .setGenerationMode(GenerationMethodEnum.AUTO_GENERATE.getCode())
                                    .setCreateUser(SecurityUtils.getUsername())
                                    .setCreateTime(new Date());
                            String lo = wmsStockInfo.getWsiStorageLoaction();
                            if (!StringUtils.isEmpty(lo)) {
                                Integer integer = Integer.valueOf(lo);
                                pickingRest1.setOutOfStock(integer);
                            }

                            pickingRestService.save(pickingRest1);

                        }
                        PickingRest pickingRest1 = pickingRestMapper.selectOne(new QueryWrapper<PickingRest>().lambda().eq(PickingRest::getConnectionId, checkManagement.getCheckDoc()));
                        //生成明细
                        PickingRestDetail pickingRestDetail = new PickingRestDetail();
                        pickingRestDetail
                                .setMaterialNumber(wmsStockInfo.getWsiMaterialNumber())
                                .setMaterialCode(wmsStockInfo.getWsiMaterialCode())
                                .setMaterialStatus(3)
                                .setGrossWeight(wmsStockInfo.getWsiGorssWeight())
                                .setNetWeight(wmsStockInfo.getWsiNetWeight())
                                .setOutgoingNumber(1)
                                .setGramWeight(wmsStockInfo.getWsiGrawWeight())
                                .setThick(wmsStockInfo.getWsiThick())
                                .setBreadth(wmsStockInfo.getWsiWidth())
                                .setRollLength(wmsStockInfo.getWsiLength())
                                .setStockInfo(wmsStockInfo.getWsiWarehourseInfo())
                                .setDepositor(SecurityUtils.getUsername())
                                .setDepositorTime(new Date())
                                .setWodDocNum(pickingRest1.getWodDocNum())
                                .setMaterialBatch(wmsStockInfo.getWsiMaterialBatch());

                        restList.add(pickingRestDetail);

                        BigDecimal bigDecimal = new BigDecimal(pickingRest1.getPlannedWeight());
                        BigDecimal bigDecimal1 = new BigDecimal(wmsStockInfo.getWsiNetWeight());
                        BigDecimal add = bigDecimal.add(bigDecimal1);
                        pickingRest1.setPlannedWeight(add.doubleValue());
                        pickingRest1.setOutgoingWeight(add.doubleValue());
                        pickingRest1.setOutgoingNumber(pickingRest1.getOutgoingNumber() + 1);
                        pickingRest1.setActualNumber(add.doubleValue());
                        pickingRestService.updateById(pickingRest1);

                        //删除库存
                        wmsStockInfoList.add(wmsStockInfo);

                    }
                    wmsStockInfoService.removeBatchByIds(wmsStockInfoList);
                    pickingRestDetailService.saveBatch(restList);


                    boolean b = wmsStockInfoService.updateBatchById(wmsList);

                    if (b) {
                        updateById(checkManagement);
                    }

                    feignService.updateStatus(3, checkManagement.getCheckDoc(), "库存盘点");

                    return b;
                } else if (data == 2) {
                    checkManagement.setCheckStatus("4");
                    if (checkManagement.getReviewBy() == null) {
                        checkManagement.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        checkManagement.setReviewBy(checkManagement.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    checkManagement.setReviewTime(new Date());
                    return updateById(checkManagement);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            } else {
                if (data == 1 || data == 2) {
                    checkManagement.setCheckStatus("2");
                    if (checkManagement.getReviewBy() == null) {
                        checkManagement.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        checkManagement.setReviewBy(checkManagement.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    checkManagement.setReviewTime(new Date());


                    return updateById(checkManagement);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            }
        } else {
            throw new GlobalException("状态为待审核和审核中的单据才能进行审核");
        }

    }

    /**
     * 盘点Pda列表
     *
     * @return
     */
    @Override
    public List<CheckListPdaDto> getCheckListPda() {
        List<CheckListPdaDto> checkListPdaDtoList = checkManagementMapper.selectListPda(SecurityUtils.getDeptId());
        List<SysDictData> statusArray = DictUtils.getDictCache("check_management_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (CheckListPdaDto checkListPdaDto : checkListPdaDtoList) {
            checkListPdaDto.setCheckStatusDict(statusMap.get(checkListPdaDto.getCheckStatus()));
        }
        return checkListPdaDtoList;
    }

    /**
     * 手持Pda明细列表
     *
     * @param checkListDetailPdaVo
     * @return
     */
    @Override
    public CheckListDetailPdaInfoDto getCheckDetailListPda(CheckListDetailPdaVo checkListDetailPdaVo) {
        //id
        Long id = checkListDetailPdaVo.getId();
        //通过id查出盘点单号
        String checkDoc = getById(id).getCheckDoc();


        List<SysDictData> statusArray = DictUtils.getDictCache("check_management_material_detail_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        CheckListDetailPdaInfoDto checkListDetailPdaInfoDto = new CheckListDetailPdaInfoDto();

        List<CheckListDetailPdaDto> checkListDetailPdaDto = checkManagementMaterialDetailMapper.getPdaMaterialDetailList(checkDoc, checkListDetailPdaVo.getMaterialCode());
        for (CheckListDetailPdaDto listDetailPdaDto : checkListDetailPdaDto) {
            listDetailPdaDto.setMaterialStatusDict(statusMap.get(listDetailPdaDto.getMaterialStatus()));
        }

        checkListDetailPdaInfoDto.setList(checkListDetailPdaDto);

        //查询盘点总数量和已扫描数
        CheckManagementDetail checkManagementDetail = checkManagementDetailMapper.selectOne(new QueryWrapper<CheckManagementDetail>().lambda().eq(CheckManagementDetail::getCheckDoc, checkDoc).eq(CheckManagementDetail::getMaterialCode, checkListDetailPdaVo.getMaterialCode()));
        checkListDetailPdaInfoDto.setStockNum(checkManagementDetail.getStockNum());
        checkListDetailPdaInfoDto.setCheckNum(checkManagementDetail.getCheckNum());

        return checkListDetailPdaInfoDto;
    }


    /**
     * 查看单据
     *
     * @param id
     * @return
     */
    @Override
    public CheckDto view(Long id) {

        CheckDto checkDto = new CheckDto();

        //通过id查出盘点单号
        CheckManagement checkManagement = checkManagementMapper.selectById(id);
        BeanUtils.copyProperties(checkManagement, checkDto);
        //通过盘点单号查出单据明细
        List<CheckDetailListDto> checkManagementDetailsList = checkManagementDetailMapper.selectDetailList(checkManagement.getCheckDoc());
        List<CheckManagementDto> list = new ArrayList<>();

        List<SysDictData> statusArray = DictUtils.getDictCache("check_management_detail_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<SysDictData> typeArray = DictUtils.getDictCache("check_management_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        checkDto.setCheckTypeDict(typeMap.get(checkManagement.getCheckType()));


        //关结原因
        String closeCause = "";

        for (CheckDetailListDto checkManagementDetail : checkManagementDetailsList) {

            if (checkManagementDetail.getCloseCause() != null && checkManagementDetail.getCloseCause() != "") {
                closeCause = closeCause + ";";
            }
            CheckManagementDto checkManagementDto = new CheckManagementDto();
            BeanUtils.copyProperties(checkManagementDetail, checkManagementDto);
            //设置状态
            checkManagementDto.setStatusDict(statusMap.get(checkManagementDetail.getStatus()));
            checkManagementDto.setStatus(checkManagementDetail.getStatus());
            list.add(checkManagementDto);
        }
        checkDto.setList(list);
        checkDto.setCloseCause(closeCause);

        //根据盘点单号查出物料明细
        //设置状态
        List<SysDictData> statusArray1 = DictUtils.getDictCache("check_management_material_detail_status");
        Map<String, String> statusMap1 = statusArray1.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<CheckManagmentMaterialDto> list1 = new ArrayList<>();
        List<CheckManagmentMaterialDto> checkManagmentMaterialDtos = checkManagementMaterialDetailMapper.selectManagmentMaterial(checkManagement.getCheckDoc());
        for (CheckManagmentMaterialDto checkManagementMaterialDetail : checkManagmentMaterialDtos) {
            CheckManagmentMaterialDto checkManagmentMaterialDto = new CheckManagmentMaterialDto();
            BeanUtils.copyProperties(checkManagementMaterialDetail, checkManagmentMaterialDto);
            //设置状态
            checkManagmentMaterialDto.setMaterialStatusDict(statusMap1.get(checkManagementMaterialDetail.getMaterialStatus()));
            checkManagmentMaterialDto.setMaterialStatusDict(checkManagementMaterialDetail.getMaterialStatus());
            list1.add(checkManagmentMaterialDto);
        }
        checkDto.setMaterialList(list1);

        return checkDto;
    }

    /**
     * 盘点信息查询
     *
     * @param checkManagementVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<CheckListDto> getList(CheckManagementVo checkManagementVo) {

        List<CheckListDto> list = checkManagementMapper.getList(checkManagementVo);

        for (CheckListDto checkListDto : list) {

            //盘点信息状态
            List<SysDictData> statusArray = DictUtils.getDictCache("check_management_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            checkListDto.setCheckStatusDict(checkListDto.getCheckStatus());
            checkListDto.setCheckStatus(statusMap.get(checkListDto.getCheckStatus()));

            //盘点类型
            List<SysDictData> typeArray = DictUtils.getDictCache("check_management_type");
            Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            checkListDto.setCheckType(checkListDto.getCheckType());
            checkListDto.setCheckTypeDict(typeMap.get(checkListDto.getCheckType()));
        }
        return list;
    }

    /**
     * 查看单据明细
     *
     * @param docNum
     * @return
     */
    @Override
    public List<CheckDetailListDto> getListDetail(String docNum) {
        List<CheckDetailListDto> checkManagementDetails = checkManagementDetailMapper.selectDetailList(docNum);

        for (CheckDetailListDto checkDetailListDto : checkManagementDetails) {

            //获取物料状态
            //盘点信息状态
            List<SysDictData> statusArray = DictUtils.getDictCache("check_management_detail_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            checkDetailListDto.setStatusDict(checkDetailListDto.getStatus());
            checkDetailListDto.setStatus(statusMap.get(checkDetailListDto.getStatus()));

        }
        return checkManagementDetails;
    }

    /**
     * 物料明细查询
     *
     * @param docNum
     * @return
     */
    @Override
    public List<CheckManagmentMaterialDto> getmaterialList(String docNum) {
        List<CheckManagmentMaterialDto> checkManagementDetails = checkManagementMaterialDetailMapper.selectManagmentMaterial(docNum);
        List<CheckManagmentMaterialDto> list = new ArrayList<>();
        for (CheckManagmentMaterialDto checkManagmentMaterialDto : checkManagementDetails) {

            //设置状态
            List<SysDictData> statusArray = DictUtils.getDictCache("check_management_material_detail_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            //设置单据状态
            checkManagmentMaterialDto.setMaterialStatusDict(checkManagmentMaterialDto.getMaterialStatus());
            //设置单据状态key
            checkManagmentMaterialDto.setMaterialStatus(statusMap.get(checkManagmentMaterialDto.getMaterialStatus()));


            BeanUtils.copyProperties(checkManagmentMaterialDto, checkManagmentMaterialDto);
            list.add(checkManagmentMaterialDto);
        }

        return list;
    }

    /**
     * 修改单据
     *
     * @param addCheckVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCheck(AddCheckVo addCheckVo) {

        //查询盘点单号
        CheckManagement checkManagement = checkManagementMapper.selectById(addCheckVo.getId());

        //删除单据
        int delete = checkManagementMapper.deleteById(addCheckVo.getId());

        if (delete > 0) {
            int delete1 = checkManagementDetailMapper.delete(new QueryWrapper<CheckManagementDetail>().lambda().eq(CheckManagementDetail::getCheckDoc, checkManagement.getCheckDoc()));
            if (delete1 > 0) {
                List<CheckManagementMaterialDetail> checkManagementMaterialDetailList = checkManagementMaterialDetailMapper.selectList(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getCheckDoc, checkManagement.getCheckDoc()));
                List<WmsStockInfo> list = new ArrayList<>();
                for (CheckManagementMaterialDetail checkManagementMaterialDetail : checkManagementMaterialDetailList) {
                    WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, checkManagementMaterialDetail.getMaterialNumber()));
                    wmsStockInfo.setWsiMaterialStatus(2);
                    list.add(wmsStockInfo);
                }
                wmsStockInfoService.updateBatchById(list);

                int delete2 = checkManagementMaterialDetailMapper.delete(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getCheckDoc, checkManagement.getCheckDoc()));
                if (delete2 <= 0) {
                    throw new GlobalException("修改失败");
                }
            } else {
                throw new GlobalException("修改失败");
            }
        } else {
            throw new GlobalException("修改失败");
        }
        //新增盘点单信息
        CheckManagement checkManagement1 = new CheckManagement();
        BeanUtils.copyProperties(addCheckVo, checkManagement1);
        //盘点单号
        checkManagement1.setCheckDoc(checkManagement.getCheckDoc());
        //盘点状态)
        checkManagement1.setCheckStatus("1");
        checkManagement1.setCreateTime(new Date());
        checkManagement1.setCreateUser(SecurityUtils.getUsername());

        boolean save = save(checkManagement1);
        if (save) {
            //新增盘点单单据信息
            List<CheckManagementVo> docList = addCheckVo.getDocList();

            List<CheckManagementDetail> list = new ArrayList<>();

            for (CheckManagementVo checkManagementVo : docList) {
                CheckManagementDetail checkManagementDetail = new CheckManagementDetail();
                BeanUtils.copyProperties(checkManagementVo, checkManagementDetail);
                checkManagementDetail.setStatus("1");
                checkManagementDetail.setCheckDoc(checkManagement.getCheckDoc());
                list.add(checkManagementDetail);
            }
            checkManagementDetailService.saveBatch(list);

            List<CheckManageMaterialVo> materialList = addCheckVo.getMaterialList();


            List<WmsStockInfo> stockInfolist = new ArrayList<>();

            List<CheckManagementMaterialDetail> checkManagementMaterialDetailList = new ArrayList<>();


            for (CheckManageMaterialVo checkManageMaterialVo : materialList) {

                //修改仓库状态为盘点
                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, checkManageMaterialVo.getMaterialNumber()));
                if (wmsStockInfo != null) {
                    wmsStockInfo.setWsiMaterialStatus(4);
                    stockInfolist.add(wmsStockInfo);
                }

                CheckManagementMaterialDetail checkManagementMaterialDetail = new CheckManagementMaterialDetail();

                BeanUtils.copyProperties(checkManageMaterialVo, checkManagementMaterialDetail);
                //设置状态为待盘点
                checkManagementMaterialDetail.setMaterialStatus("1");
                checkManagementMaterialDetail.setCreateTime(new Date());
                checkManagementMaterialDetail.setCreateUser(SecurityUtils.getUsername());
                checkManagementMaterialDetail.setCheckDoc(checkManagement.getCheckDoc());
                checkManagementMaterialDetailList.add(checkManagementMaterialDetail);

            }
            boolean update = wmsStockInfoService.updateBatchById(stockInfolist);
            if (update) {
                checkManagementMaterialDetailService.saveBatch(checkManagementMaterialDetailList);
            }
        } else {
            throw new GlobalException("新增失败");
        }

        return save;

    }

    /**
     * 盘点
     *
     * @param pdVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PdDto pdCheck(PdVo pdVo) {
        //获取输入的值
        String inputValue = pdVo.getInputValue();
        //盘点类别
        String type = pdVo.getType();
        //获取步骤
        String step = pdVo.getStep();
        //定义返回值
        PdDto pdDto = new PdDto();
        //物料料号
        String materialCode = pdVo.getMaterialCode();
        //库位编码
        String pdStock = pdVo.getPdStock();
        //根据id查出当前的关联单号
        CheckManagement checkManagement = checkManagementMapper.selectById(pdVo.getId());
        String checkDoc = checkManagement.getCheckDoc();
        //总量盘点
        if ("1".equals(type)) {

            if ("1".equals(step)) {
                //WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(inputValue);

                Warehouse warehouse = warehouseMapper.selectOne(new QueryWrapper<Warehouse>().lambda().eq(Warehouse::getWarehouseCode, inputValue));

                if (warehouse == null) {
                    pdDto.setMessage("该库位不存在");
                    pdDto.setCode("500");
                    return pdDto;
                } else {
                    //设置库位信息
                    pdDto.setStockInfo(warehouse.getWarehouseName());
                    //查询当前物料在该库区库位的数量
                    //Long sumMaterial = wmsStockInfoMapper.getMaterialNumber(materialCode, warehouse.getWarehouseCode());

                    WarehouseStringDto warehouseStringDto = warehouseService.getWarehouseCode(warehouse.getWarehouseCode());

                    List<CheckManagementMaterialDetail> sumList = checkManagementMaterialDetailMapper.selectList(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getCheckDoc, checkDoc).eq(CheckManagementMaterialDetail::getMaterialCode, materialCode).eq(CheckManagementMaterialDetail::getStockInfo, warehouseStringDto.getCombinationName()));


                    //String[] split = warehouseCode.split("-");
                    //设置提示信息
                    pdDto.setMessage(warehouse.getWarehouseName() + "物料的库存数量为" + sumList.size() + ",请输入实际盘点数量");
                    //查询物料在盘点单据明细中的数量
                    //CheckManagementDetail checkManagementDetail = checkManagementDetailMapper.selectOne(new QueryWrapper<CheckManagementDetail>().lambda().eq(CheckManagementDetail::getMaterialCode, pdVo.getMaterialCode()));
                    //pdDto.setSumNumber(checkManagementDetail.getStockNum() + "");
                    pdDto.setPdStock(warehouse.getWarehouseCode());
                    pdDto.setCode("200");
                    return pdDto;
                }
            } else {
                //Warehouse warehouse = warehouseMapper.selectOne(new QueryWrapper<Warehouse>().lambda().eq(Warehouse::getWarehouseCode, pdVo.getPdStock()));
                //WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(inputValue);
                //查询当前物料在该库区库位的数量
                //Long sumMaterial = wmsStockInfoMapper.getMaterialNumber(materialCode, pdVo.getPdStock());

                WarehouseStringDto warehouseStringDto = warehouseService.getWarehouseCode(pdVo.getPdStock());

                List<CheckManagementMaterialDetail> sumList = checkManagementMaterialDetailMapper.selectList(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getCheckDoc, checkDoc).eq(CheckManagementMaterialDetail::getMaterialCode, materialCode).eq(CheckManagementMaterialDetail::getStockInfo, warehouseStringDto.getCombinationName()));

                //盘点当前输入的值和仓库的数量进行比较
                long input = Long.parseLong(inputValue);

                List<CheckManagementMaterialDetail> list = new ArrayList<>();
                if (input == sumList.size()) {
                    //修改当前盘点物料明细状态为已盘点
                    for (CheckManagementMaterialDetail checkManagementMaterialDetail : sumList) {
                        if (checkManagementMaterialDetail != null) {
                            //修改物料明细状态为已盘点
                            checkManagementMaterialDetail.setMaterialStatus("2");
                            checkManagementMaterialDetail.setCheckNum(1L);
                            checkManagementMaterialDetail.setCreateUser(SecurityUtils.getUsername());
                            checkManagementMaterialDetail.setCreateTime(new Date());

                            //设置物料明细盈亏数量为0
                            checkManagementMaterialDetail.setPhaseNum(0L);

                            list.add(checkManagementMaterialDetail);
                        }
                    }
                    //修改物料明细为已盘点
                    checkManagementMaterialDetailService.updateBatchById(list);

                    //修改物料单据状态为盘点中
                    checkManagement.setCheckStatus("2");
                    updateById(checkManagement);

                    //修改单据明细为盘点中
                    CheckManagementDetail checkManagementDetail = checkManagementDetailMapper.selectOne(new QueryWrapper<CheckManagementDetail>().lambda().eq(CheckManagementDetail::getCheckDoc, checkDoc).eq(CheckManagementDetail::getMaterialCode, pdVo.getMaterialCode()));
                    checkManagementDetail.setStatus("2");
                    checkManagementDetail.setCheckNum(input);
                    checkManagementDetailMapper.updateById(checkManagementDetail);

                    //查询当前仓储信息中
                    pdDto.setMessage("此批物料盘点完成");
                    pdDto.setCode("200");
                } else {
                    pdDto.setMessage("输入数量与库存数量存在差异,请清点后再次输入，或切换到明细盘点");
                    pdDto.setCode("200");
                }

            }
        } else if ("2".equals(type)) {

            if ("1".equals(step)) {
                //WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(inputValue);

                Warehouse warehouse = warehouseMapper.selectOne(new QueryWrapper<Warehouse>().lambda().eq(Warehouse::getWarehouseCode, inputValue));
                if (warehouse == null) {
                    pdDto.setMessage("该库位不存在");
                    pdDto.setCode("500");
                    return pdDto;

                } else {
                    //设置库位信息
                    pdDto.setStockInfo(warehouse.getWarehouseName());
                    //设置提示信息
                    pdDto.setMessage("请输入物料条码");
                    pdDto.setPdStock(warehouse.getWarehouseCode());
                    pdDto.setCode("200");
                    return pdDto;
                }
            } else {

                //查询当前明细的号码
                WmsStockInfo wmsStockInfoCode = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue));

                //如果在库存中没有这个单据号码，提示该物料号码不存在
                if (wmsStockInfoCode == null) {
                    pdDto.setMessage("该物料号码不存在");
                    pdDto.setCode("500");
                    return pdDto;
                }

                //比较盘点所选物料和此物料是否一致
                if (!wmsStockInfoCode.getWsiMaterialCode().equals(pdVo.getMaterialCode())) {
                    pdDto.setMessage("输入的物料号码对应的物料编码和所选物料编码不匹配");
                    pdDto.setCode("500");
                    return pdDto;
                }


                //判断明细中是否有这个号码
                CheckManagementMaterialDetail numberList = checkManagementMaterialDetailMapper.selectOne(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getMaterialNumber, inputValue).eq(CheckManagementMaterialDetail::getCheckDoc, checkDoc));

                if (numberList != null) {
                    String materialStatus = numberList.getMaterialStatus();
                    //如果物料明细中状态不为待盘点
                    if (!"1".equals(materialStatus)) {
                        throw new GlobalException("只能对待盘点状态的单据号码进行盘点操作");
                    }
                }


                //是所选物料，不是所选单据
                if (numberList == null) {
                    //弹窗提示(该物料不是此单据下的关联条码,是否确认盘点)
                    pdDto.setWindowMessage("该物料不是此单据下的关联条码,是否确认盘点");
                    pdDto.setWindowType("1");
                    pdDto.setCode("200");
                    return pdDto;
                }


                //查询库存中盘点中的物料号码
                WmsStockInfo wmsStockInfo2 = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue).eq(WmsStockInfo::getWsiMaterialStatus, 4));


                //是所选物料,同一单据,库位不一样
                if (wmsStockInfo2 != null) {
                    //取出库位,判断当前库位是否和新库位一致
                    WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue));
                    String stockInfo = wmsStockInfo.getWsiStorageLoaction();

                    //pdStock:前端传的库位编码
                    Warehouse warehouse = warehouseMapper.selectOne(new QueryWrapper<Warehouse>().lambda().eq(Warehouse::getWarehouseCode, pdStock));

                    //如果是该单据条码，但不是本库位条码
                    if (!stockInfo.equals(warehouse.getId() + "")) {
                        //弹窗提示
                        pdDto.setWindowType("2");
                        pdDto.setWindowMessage("该物料不是此库位下的关联条码,是否确认盘点");
                        pdDto.setCode("200");
                        return pdDto;

                    } else {
                        pdDto.setMessage("物料号码:" + inputValue + ",净重:" + wmsStockInfo.getWsiNetWeight() + ",数量:1,已盘点");
                        pdDto.setWindowMessage("");

                        //修改盘点单据状态为盘点中
                        CheckManagementDetail checkManagementDetail = checkManagementDetailMapper.selectOne(new QueryWrapper<CheckManagementDetail>().lambda().eq(CheckManagementDetail::getMaterialCode, pdVo.getMaterialCode()).eq(CheckManagementDetail::getCheckDoc, checkDoc));
                        checkManagementDetail.setStatus("2");
                        //盘点数量累加
                        Long checkNum = checkManagementDetail.getCheckNum();
                        if (checkNum == null) {
                            checkNum = 0L;
                        }
                        checkManagementDetail.setCheckNum(checkNum + 1);

                        checkManagementDetailMapper.updateById(checkManagementDetail);
                        //设置已扫描数
                        pdDto.setNumber(checkManagementDetail.getCheckNum() + "");
                        //更改物料条码为已盘点
                        CheckManagementMaterialDetail checkManagementMaterialDetail = checkManagementMaterialDetailMapper.selectOne(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getMaterialNumber, inputValue).eq(CheckManagementMaterialDetail::getCheckDoc, checkDoc));
                        checkManagementMaterialDetail.setMaterialStatus("2");
                        checkManagementMaterialDetail.setCreateTime(new Date());
                        checkManagementMaterialDetail.setCreateUser(SecurityUtils.getUsername());
                        //盈亏数给0
                        checkManagementMaterialDetail.setPhaseNum(0L);
                        //盘点数量给1
                        checkManagementMaterialDetail.setCheckNum(1L);
                        checkManagementMaterialDetailService.updateById(checkManagementMaterialDetail);
                        //单据明细修改为盘点中
                        checkManagement.setCheckStatus("2");
                        updateById(checkManagement);
                        pdDto.setCode("200");

                    }
                } else {
                    pdDto.setWindowMessage("该物料不是盘点状态或者物料号码不存在");
                    pdDto.setCode("500");
                    return pdDto;
                }
            }

        }

        return pdDto;
    }

    /**
     * 弹窗提醒
     *
     * @param pdVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PdDto openWindow(PdVo pdVo) throws Exception {
        //获取弹窗类别
        String windowType = pdVo.getWindowType();
        //号码
        String inputValue = pdVo.getInputValue();
        PdDto pdDto = new PdDto();
        CheckManagement checkManagement = checkManagementMapper.selectById(pdVo.getId());
        String checkDoc = checkManagement.getCheckDoc();
        if ("1".equals(windowType) || "2".equals(windowType)) {
            //通过号码查出库存中的重量
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, inputValue));

            if (wmsStockInfo == null) {
                pdDto.setCode("500");
                pdDto.setMessage("该号码不存在,请核实后扫描");
                return pdDto;
            }

            //如果是
            if ("1".equals(windowType)) {
                pdDto.setMessage("物料号码:" + inputValue + ",净重:" + wmsStockInfo.getWsiNetWeight() + "数量1,盘盈");
                //修改盘点单据状态为盘点中
                CheckManagementDetail checkManagementDetail = checkManagementDetailMapper.selectOne(new QueryWrapper<CheckManagementDetail>().lambda().eq(CheckManagementDetail::getMaterialCode, pdVo.getMaterialCode()).eq(CheckManagementDetail::getCheckDoc, checkManagement.getCheckDoc()));
                checkManagementDetail.setStatus("2");
                //盘点数量累加
                Long checkNum = checkManagementDetail.getCheckNum();
                if (checkNum == null) {
                    checkNum = 0L;
                }
                checkManagementDetail.setCheckNum(checkNum + 1L);
            /*
            Long phaseNum = checkManagementDetail.getPhaseNum();
            if (phaseNum==null){
                phaseNum=0L;
            }
            //设置盈亏数量
            checkManagementDetail.setPhaseNum(phaseNum+1L);*/
                checkManagementDetailMapper.updateById(checkManagementDetail);
                //设置已扫描数
                pdDto.setNumber(checkManagementDetail.getCheckNum() + "");
                //设置总条码数
                pdDto.setTotalNumber(checkManagementDetail.getStockNum() + "");

                WarehouseStringDto warehouseStringDto = warehouseService.getWarehouseCode(pdVo.getPdStock());


                CheckManagementMaterialDetail checkManagementMaterialDetail1 = new CheckManagementMaterialDetail();
                checkManagementMaterialDetail1.setMaterialNumber(inputValue);
                checkManagementMaterialDetail1.setMaterialCode(wmsStockInfo.getWsiMaterialCode());
                checkManagementMaterialDetail1.setMaterialStatus("4");
                checkManagementMaterialDetail1.setStockNum(1L);
                checkManagementMaterialDetail1.setCheckNum(1L);
                checkManagementMaterialDetail1.setCheckDoc(checkDoc);
                checkManagementMaterialDetail1.setStockInfo(warehouseStringDto.getCombinationName());
                checkManagementMaterialDetail1.setCreateUser(SecurityUtils.getUsername());
                checkManagementMaterialDetail1.setCreateTime(new Date());
                checkManagementMaterialDetailService.save(checkManagementMaterialDetail1);

                //重新绑定库区库位
                wmsStockInfo.setWsiWarehourse(warehouseStringDto.getCkId() + "");
                wmsStockInfo.setWsiReservoirArea(warehouseStringDto.getKqId() + "");
                wmsStockInfo.setWsiStorageLoaction(warehouseStringDto.getKwId() + "");
                wmsStockInfo.setWsiWarehourseInfo(warehouseStringDto.getCombinationName());
                wmsStockInfo.setWsiMaterialStatus(4);//调拨
                wmsStockInfoService.updateById(wmsStockInfo);


            } else if ("2".equals(windowType)) {

                pdDto.setMessage("物料号码:" + inputValue + ",净重:" + wmsStockInfo.getWsiNetWeight() + "数量1,已盘点");
                //修改盘点单据状态为盘点中
                CheckManagementDetail checkManagementDetail = checkManagementDetailMapper.selectOne(new QueryWrapper<CheckManagementDetail>().lambda().eq(CheckManagementDetail::getMaterialCode, pdVo.getMaterialCode()).eq(CheckManagementDetail::getCheckDoc, checkDoc));
                checkManagementDetail.setStatus("2");
                //盘点数量累加
                Long checkNum = checkManagementDetail.getCheckNum();
                if (checkNum == null) {
                    checkNum = 0L;
                }
                checkManagementDetail.setCheckNum(checkNum + 1);

                Long phaseNum = checkManagementDetail.getPhaseNum();
                if (phaseNum == null) {
                    phaseNum = 0L;
                }
                //checkManagementDetail.setPhaseNum(phaseNum + 1);
                checkManagementDetailMapper.updateById(checkManagementDetail);
                //设置已扫描数
                pdDto.setNumber(checkManagementDetail.getCheckNum() + "");
                //设置总条码数
                pdDto.setTotalNumber(checkManagementDetail.getStockNum() + "");

                boolean b = checkManagementDetailService.updateById(checkManagementDetail);
                if (b) {

                    WarehouseStringDto warehouseStringDto = warehouseService.getWarehouseCode(pdVo.getPdStock());
                    //重新绑定库区库位
                    wmsStockInfo.setWsiWarehourse(warehouseStringDto.getCkId() + "");
                    wmsStockInfo.setWsiReservoirArea(warehouseStringDto.getKqId() + "");
                    wmsStockInfo.setWsiStorageLoaction(warehouseStringDto.getKwId() + "");
                    wmsStockInfo.setWsiWarehourseInfo(warehouseStringDto.getCombinationName());
                    wmsStockInfoService.updateById(wmsStockInfo);

                    CheckManagementMaterialDetail checkManagementMaterialDetail = checkManagementMaterialDetailMapper.selectOne(new QueryWrapper<CheckManagementMaterialDetail>()
                            .lambda()
                            .eq(CheckManagementMaterialDetail::getMaterialNumber, inputValue)
                            .eq(CheckManagementMaterialDetail::getCheckDoc,checkManagement.getCheckDoc()));
                    checkManagementMaterialDetail.setStockInfo(warehouseStringDto.getCombinationName());
                    checkManagementMaterialDetail.setMaterialStatus("2");//已盘点
                    checkManagementMaterialDetail.setCheckNum(1L);

                    checkManagementMaterialDetail.setCreateTime(new Date());
                    checkManagementMaterialDetail.setCreateUser(SecurityUtils.getUsername());

                    //设置物料明细盈亏数量为0
                    checkManagementMaterialDetail.setPhaseNum(0L);
                    //盘点数量+1
                    checkManagementMaterialDetailService.updateById(checkManagementMaterialDetail);
                }
            }
        } else if ("3".equals(windowType)) {

            //修改单据状态为待审核
            checkManagement.setCheckStatus("3");

            //新增审核代办
            SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();

            sysWorkbenchAuditAgentVo.setDocConfig("warehouse:inside:InventoryCount:examine");
            sysWorkbenchAuditAgentVo.setReceiptName("库存盘点");
            sysWorkbenchAuditAgentVo.setReceiptNumber(checkManagement.getCheckDoc());//盘点单号
            sysWorkbenchAuditAgentVo.setStatus(1);//待审核
            sysWorkbenchAuditAgentVo.setReceiptContent("有单据待审核,请及时审核");

            feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

            updateById(checkManagement);

            //查询单据明细列表
            List<CheckManagementDetail> checkManagementDetails = checkManagementDetailMapper.selectList(new QueryWrapper<CheckManagementDetail>().lambda().eq(CheckManagementDetail::getCheckDoc, checkDoc));

            List<CheckManagementMaterialDetail> checkManagementMaterialDetails1 = new ArrayList<>();


            //把物料明细中为待盘点状态的设置为盈亏
            List<CheckManagementMaterialDetail> checkManagementMaterialDetails = checkManagementMaterialDetailMapper.selectList(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getCheckDoc, checkDoc));
            for (CheckManagementMaterialDetail checkManagementMaterialDetail : checkManagementMaterialDetails) {
                String materialStatus = checkManagementMaterialDetail.getMaterialStatus();
                if ("1".equals(materialStatus)) {

                    //修改物料明细状态为盘亏
                    checkManagementMaterialDetail.setMaterialStatus("3");
                    checkManagementMaterialDetail.setCheckNum(0L);
                    checkManagementMaterialDetail.setPhaseNum(1L);

                    checkManagementMaterialDetail.setCreateTime(new Date());
                    checkManagementMaterialDetail.setCreateUser(SecurityUtils.getUsername());

                    checkManagementMaterialDetails1.add(checkManagementMaterialDetail);


                }
            }
            boolean b = checkManagementMaterialDetailService.updateBatchById(checkManagementMaterialDetails1);

            List<CheckManagementDetail> list1 = new ArrayList<>();

            if (b) {
                for (CheckManagementDetail checkManagementDetail : checkManagementDetails) {
                    //盘盈
                    Long lucid = checkManagementMaterialDetailMapper.selectCount(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getMaterialCode, checkManagementDetail.getMaterialCode()).eq(CheckManagementMaterialDetail::getMaterialStatus, "4").eq(CheckManagementMaterialDetail::getCheckDoc, checkDoc));

                    //盘亏
                    Long loss = checkManagementMaterialDetailMapper.selectCount(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getMaterialCode, checkManagementDetail.getMaterialCode()).eq(CheckManagementMaterialDetail::getMaterialStatus, "3").eq(CheckManagementMaterialDetail::getCheckDoc, checkDoc));


                    if ("1".equals(checkManagementDetail.getStatus())) {
                        //设置单据明细为盘点中
                        checkManagementDetail.setStatus("2");
                    }

                    checkManagementDetail.setPhaseNum(lucid - loss);
                    //设置盈亏数量
                    list1.add(checkManagementDetail);


                }
                checkManagementDetailService.updateBatchById(list1);
            }

            if (!b) {
                throw new GlobalException("盘点完成失败");
            }
        } else if ("4".equals(windowType)) {
            List<CheckManagementDetail> checkManagementDetails = checkManagementDetailMapper.selectList(new QueryWrapper<CheckManagementDetail>().lambda().eq(CheckManagementDetail::getCheckDoc, checkDoc));
            //修改单据状态为待审核
            checkManagement.setCheckStatus("3");

            //新增审核代办
            SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();

            sysWorkbenchAuditAgentVo.setDocConfig("warehouse:inside:InventoryCount:examine");
            sysWorkbenchAuditAgentVo.setReceiptName("库存盘点");
            sysWorkbenchAuditAgentVo.setReceiptNumber(checkManagement.getCheckDoc());//盘点单号
            sysWorkbenchAuditAgentVo.setStatus(1);//待审核
            sysWorkbenchAuditAgentVo.setReceiptContent("有单据待审核,请及时审核");

            feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

            updateById(checkManagement);

            for (CheckManagementDetail checkManagementDetail : checkManagementDetails) {
                //盘盈
                Long lucid = checkManagementMaterialDetailMapper.selectCount(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getMaterialCode, checkManagementDetail.getMaterialCode()).eq(CheckManagementMaterialDetail::getMaterialStatus, "4").eq(CheckManagementMaterialDetail::getCheckDoc, checkDoc));

                //盘亏
                Long loss = checkManagementMaterialDetailMapper.selectCount(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getMaterialCode, checkManagementDetail.getMaterialCode()).eq(CheckManagementMaterialDetail::getMaterialStatus, "3").eq(CheckManagementMaterialDetail::getCheckDoc, checkDoc));

                //设置单据明细为盘点中
                if ("1".equals(checkManagementDetail.getStatus())) {
                    checkManagementDetail.setStatus("2");
                }


                checkManagementDetail.setPhaseNum(lucid - loss);
                //设置盈亏数量
                int update = checkManagementDetailMapper.updateById(checkManagementDetail);

            }
        }
        pdDto.setCode("200");
        return pdDto;
    }

    /**
     * 盘点完成
     *
     * @param pdVo
     * @return
     */
    @Override
    public PdDto checkInventory(PdVo pdVo) {
        //查询盘点单号
        CheckManagement checkManagement = checkManagementMapper.selectById(pdVo.getId());
        String checkDoc = checkManagement.getCheckDoc();
        //查询盘点单据是否有待盘点的单据
        List<CheckManagementMaterialDetail> checkManagementMaterialDetailList = checkManagementMaterialDetailMapper.selectList(new QueryWrapper<CheckManagementMaterialDetail>().lambda().eq(CheckManagementMaterialDetail::getCheckDoc, checkDoc));

        PdDto pdDto = new PdDto();

        boolean flag = false;

        for (CheckManagementMaterialDetail checkManagementMaterialDetail : checkManagementMaterialDetailList) {
            //获取状态
            String status = checkManagementMaterialDetail.getMaterialStatus();
            if ("1".equals(status)) {
                flag = true;
                break;
            }
        }

        if (flag) {
            //弹窗提示
            pdDto.setWindowType("3");
            pdDto.setWindowMessage("存在未盘点的物料,是否确定完成");
            return pdDto;
        } else {
            //弹窗提示
            pdDto.setWindowType("4");
            pdDto.setWindowMessage("是否确定完成");
            return pdDto;

        }

    }


}
